<template>
	<v-layout type="main">
		<div class="alike-lis-header">
			<div class="lis-header-left">
				<div class="add-btn" @click="addModelConvertDialog">+ 新增</div>

				<div class="btns-switch">
					<div @click="isCard = true">
						<img src="@/assets/img/List_card.png" v-if="isCard" />
						<img src="@/assets/img/list_nocard.png" v-else />
					</div>
					<div @click="isCard = false">
						<img src="@/assets/img/list_nolist.png" v-if="isCard" />
						<img src="@/assets/img/list_list.png" v-else />
					</div>
				</div>

				<div class="search-box">
					<el-input
						prefix-icon="el-icon-search"
						v-model="Pagedata.name"
						class="search"
						placeholder=""
						@input="searchChange"
					/>
				</div>
			</div>

			<div class="lis-header-right">
				<el-select size="mini" placeholder="请选择" v-model="showThisActive" @change="getData">
					<el-option label="我的模型" value="0"></el-option>
					<el-option label="共享模型" value="1"></el-option>
				</el-select>
			</div>
		</div>

		<div class="has-ver-table-layout">
			<div class="table-layout" v-if="!isCard">
				<el-table :data="tableData" class="myself-table">
					<el-table-column prop="name" :label="app_user === 'htzny' ? '待量化模型' : '名称'">
						<template slot-scope="{ row }">
							<el-button type="text" @click="getVersions(row)" slot="reference" v-if="row.model">
								{{ row.model.name }}
							</el-button>
						</template>
					</el-table-column>

					<el-table-column prop="model.desc" label="描述信息">
						<template slot-scope="{ row }">
							<el-popover placement="top" width="320" trigger="hover" :content="row.model.desc" v-if="row.model">
								<span class="desc" slot="reference">{{ row.model.desc }}</span>
							</el-popover>
						</template>
					</el-table-column>

					<el-table-column prop="node_group_list[0].image.name" label="镜像" />
					<el-table-column prop="node_group_list[0].product.name" label="资源组" />

					<el-table-column prop="status" label="状态">
						<template slot-scope="{ row }">
							<span :class="['alick-list-status', row.status]">●{{ statusMap[row.status] }}</span>
						</template>
					</el-table-column>

					<el-table-column prop="model.version_count" label="版本数量" />
					<el-table-column prop="create_user.nick_name" label="创建用户" />
					<el-table-column prop="update_user.nick_name" label="更新用户" />
					<el-table-column width="180" prop="update_time" label="更新时间" />

					<!-- <el-table-column label="运行时长">
            <template slot-scope="{ row }">
              {{ countRanTime(row.resource && row.resource.start_time) }}
            </template>
          </el-table-column> -->

          <el-table-column label="操作" width="200">
            <template slot-scope="{ row }">
              <el-popover
                  placement="top"
                  width="80"
                  trigger="click"
                  v-model="row.visible"
              >
                <p>您确定要删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="row.visible = false"
                  >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="del(row)"
                  >确定</el-button
                  >
                </div>
                <el-button type="text" slot="reference">删除</el-button>
              </el-popover>
            </template>
          </el-table-column>
				</el-table>
			</div>

			<ul class="alike-lis" v-else>
				<li v-for="(item, index) in tableData" :key="index">
					<div class="alike-lis-box">
						<div class="alike-lis-pic" @click="getVersions(item)">
							<v-image :src="item.avatar ? item.avatar : require('@/assets/img/drone3.jpg')" alt="" />
						</div>
						<div class="alike-lis-word">
							<div class="alike-lis-title">
								<span>
									<span @click="$router.push({ path: '/model/code', query: { id: item.id } })">
										{{ item.name }}
									</span>
									<template v-if="typeof item.status === 'string'">
										<el-tag
											type="danger"
											effect="dark"
											size="mini"
											v-if="['terminated', 'failed', 'Failed'].includes(item.status)"
										>
											{{ statusMap[item.status] }}
										</el-tag>
										<el-tag
											type="success"
											effect="dark"
											size="mini"
											v-else-if="['completed', 'Succeeded', 'running', 'Running'].includes(item.status)"
										>
											{{ statusMap[item.status] }}
										</el-tag>
										<el-tag type="warning" effect="dark" size="mini" v-else>
											{{ statusMap[item.status] }}
										</el-tag>
									</template>
								</span>
							</div>

							<p class="alike-lis-hint">{{ item.desc }}</p>
							<p class="alike-lis-hint">版本数量：{{ item.version_index }}</p>

							<div class="alike-lis-user">
								<span class="user-name">创建人：{{ item.create_user.nick_name }}</span>
								<span class="date">{{ item.create_time }}</span>
							</div>
						</div>
					</div>
				</li>
			</ul>
		</div>

		<div class="pagination-box">
			<el-pagination
				background
				class="pagination"
				layout="total, prev, pager, next, jumper"
				:page-size="Pagedata.pageSize"
				:current-page.sync="Pagedata.pageNum"
				@current-change="handleCurrentChange"
				:total="Pagedata.total"
			>
			</el-pagination>
		</div>

		<el-drawer title="版本列表" :visible.sync="drawerShow" direction="rtl">
			<ul class="version-list">
				<li
					class="version-item"
					v-for="(item, i) in modelAllVersions"
					:key="item.id"
					@click="getModelConvert(modelAllVersions[i], current)"
				>
					<p>
						<span class="title">{{ item.version }}</span>
						<span class="update-time">更新时间：{{ item.update_time }}</span>
					</p>
					<span class="commit">{{ item.commit_msg }}</span>
				</li>
			</ul>
		</el-drawer>

		<el-dialog :visible.sync="showModelEvaDialog" title="模型量化" width="840px">
			<el-form class="form myself-form" ref="evaModelForm" :model="evaModelForm" label-width="120px">
				<div v-if="active == 1">
					<el-form-item label="模型名称" prop="version">
						<el-select
							v-model="evaModelForm.name"
							value-key="id"
							@change="modelAddEvaNameChange"
							style="width:100%;"
							:popper-append-to-body="false"
							popper-class="select-popper"
							placeholder="请选择"
						>
							<el-option v-for="item in modelEvaList" :key="item.id" :label="item.name" :value="item"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="模型版本">
						<el-select
							v-model="evaModelForm.version"
							value-key="id"
							@change="modelAddEvaVersionChange"
							style="width:100%;"
							:popper-append-to-body="false"
							popper-class="select-popper"
							placeholder="请选择"
							disabled
						>
							<el-option v-for="item in versionOptions" :key="item.id" :label="item.version" :value="item"> </el-option>
						</el-select>
					</el-form-item>

					<!-- <el-form-item label="转换方式">
						<el-radio-group v-model="evaModelForm.currentWay" @input="wayChange">
							<el-radio label="1">转换</el-radio>
							<el-radio label="2">量化</el-radio>
						</el-radio-group>
					</el-form-item> -->

					<el-form-item label="类型" prop="version" v-if="evaModelForm.currentWay === '2'">
						<el-select v-model="evaModelForm.type" class="full-extent-select">
							<el-option
								v-for="(item, i) in typeValue.filter((item) => item.type === evaModelForm.currentWay)"
								:value="item.value"
								:label="item.label"
								:key="i"
							>
							</el-option>
						</el-select>
					</el-form-item>

					<div v-if="evaModelForm.currentWay === '1'">
						<el-form-item label="来源格式" prop="version">
							<el-select v-model="evaModelForm.source_format" class="full-extent-select">
								<el-option v-for="(item, i) in format" :value="item" :label="item" :key="i"> </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="目标格式" prop="version">
							<el-select v-model="evaModelForm.target_format" class="full-extent-select">
								<el-option v-for="(item, i) in format" :value="item" :label="item" :key="i"> </el-option>
							</el-select>
						</el-form-item>
					</div>
					<el-form-item label="转换镜像">
						<el-select v-model="node_group_list.image_id" disabled class="full-extent-select">
							<el-option v-for="item in imageOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="资源组">
						<el-select v-model="node_group_list.product_id" class="full-extent-select">
							<el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="数据集" v-if="evaModelForm.currentWay === '2' && evaModelForm.type === 3">
						<plug-dataset :dataset_list="evaModelForm.dataset_list" @infoDataset="infoDataset" />
					</el-form-item>
				</div>

				<!-- v-if="!showDiv || active == 2" -->
				<el-form-item label="">
					<el-button type="primary" @click="commitModelEva(detailData.id)">确定</el-button>
					<el-button class="none-type" @click="showModelEvaDialog = false">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</v-layout>
</template>

<script>
import plugDataset from "@/components/module/plug-in-dataset";
import { mapActions, mapState } from "vuex";
import { getModels, delModel } from "@/api/model";
import { getAllModelVersions } from "@/api/modelversion";
// import { getAllModelEvabyModelVersion, addModelEvaluatio } from '@/api/modelEva'
import {
	getAllmodelConvertbyModelVersion,
	getModelConverts,
	addModelConvert,
	delModelConvert,
} from "@/api/modelConvert";
// import { getAllmodelConvertbyModelVersion, addModelConvert } from '@/api/modelConvert'
import { getAllModelEvaluationTypes } from "@/api/modelEvaType";
import { getAllProducts } from "@/api/product";
import { getAllImages } from "@/api/image";
// import { paramMap } from '@/utils/maps'
export default {
	data() {
		return {
			modelAllVersions: [],
			way: [
				{ label: "转换", value: 1 },
				{ label: "量化", value: 2 },
			],
			typeValue: [
				{ label: "格式转换", value: 1, type: "1" },
				{ label: "权值量化", value: 2, type: "2" },
				{ label: "知识蒸馏", value: 3, type: "2" },
				{ label: "模型剪枝", value: 4, type: "2" },
				{ label: "矩阵分解", value: 5, type: "2" },
				{ label: "低秩近似", value: 6, type: "2" },
			],
			format: ["pt", "pth", "onnx", "trt"],
			showModelEvaDialog: false,
			evaModelForm: {}, //模型评估
			modelEvaTyleOptions: [], //模型评估类型选项
			active: 1,
			node_group_list: {
				type: 1,
				pod_num: 1,
			},
			showDiv: false,
			detailData: {},
			version: {},
			productOptions: [], //资源组选项
			imageOptions: [], //评估镜像选项
			showThisActive: "0",
			// list_flag: paramMap['list_flag'],
			isCard: false,
			tableData: [],
			Pagedata: {
				pageNum: 1,
				pageSize: 12,
				total: 0,
				name: "",
			},
			drawerShow: false,
			current: {},
			versionOptions: [],
			modelEvaList: [],
			app_user: process.env.VUE_APP_USER,
		};
	},
	created() {
		this.Pagedata = { ...this.Pagedata, pageNum: this.pageNum, name: this.searchValue };
	},
	mounted() {
		this.getData();
		this.getAllModelEvaTypes();
		this.getImageList();
		this.getProductList();
	},
	computed: mapState({
		pageNum: (state) => state.menuStore.pageData.pageNum,
		searchValue: (state) => state.menuStore.searchValue,
	}),
	methods: {
		...mapActions(["updatePageNum", "updateSearch"]),
		wayChange() {},
		async getVersions(data) {
			console.log("data", data);
			// let res = await getAllModelVersions({ model_id: data.id });
			// this.getModelConvert(res.data[res.data.length - 1], data);

			this.getModelConvert(data.model_version_id, data);

			// if (data.latest_versions.length > 1) {
			// 	this.drawerShowHandler(data);
			// } else {
			// 	this.getModelConvert(data.latest_versions[0], data);
			// }
		},
		async getModelConvert(version, item) {
			console.log(version);
			console.log(item);
			this.detailData = item;
			this.version = version;
			let ret = await getAllmodelConvertbyModelVersion({ id: version });

			this.toModelEva(ret.data.id, item.id);
			// if (ret.data) {
			// 	this.toModelEva(ret.data.id, item.id);
			// } else {
			// 	this.showModelEvaDialog = true;
			// 	this.evaModelForm.model_id = item.id;
			// 	this.evaModelForm.model_version_id = version.id;
			// }
		},
		infoDataset(datasets) {
			this.evaModelForm.dataset_list = [];
			datasets.forEach((e) => {
				e.dataset_id = e.id;
				e.dataset = {
					name: e.name,
					alias: e.alias,
					id: e.id,
				};
			});
			this.evaModelForm.dataset_list = datasets;
			console.log("infoDataset", datasets);
		},
		async addModelConvertDialog() {
			this.showModelEvaDialog = true;
			this.evaModelForm = {
				currentWay: "2",
				version: {},
			};
			this.node_group_list = {
				type: 1,
				pod_num: 1,
				image_id: this.imageOptions[0].id,
			};

			let res = await getModels({ visibility: this.showThisActive });
			this.modelEvaList = res.data.list;
		},
		modelAddEvaNameChange(data) {
			this.$nextTick(async () => {
				let resVer = await getAllModelVersions({ model_id: data.id });
				this.versionOptions = resVer.data;
				console.log(this.versionOptions);
				this.evaModelForm.version = this.versionOptions[this.versionOptions.length - 1];
			});
		},
		modelAddEvaVersionChange() {},
		// 新建模型评估
		async commitModelEva(id) {
			console.log(id);

			if (this.evaModelForm.currentWay !== "2" || this.evaModelForm.type !== 3) {
				this.evaModelForm.dataset_list = [];
			}

			// this.evaModelForm.type_id = this.evaModelForm.type.id;
			this.evaModelForm.type_id = "1584070974760013";
			this.evaModelForm.model_id = this.evaModelForm.name.id;
			this.evaModelForm.model_version_id = this.evaModelForm.version.id;
			this.evaModelForm.node_group_list = [this.node_group_list];
			this.evaModelForm.port_list = this.port_list;
			// this.evaModelForm.image_id = this.node_group_list.image_id;
			this.evaModelForm.image_id = this.imageOptions[0];

			if (this.evaModelForm.currentWay === "1") {
				this.evaModelForm.type = 1;
			}

			if (this.evaModelForm.currentWay === "2") {
				this.evaModelForm.target_format = "1";
				this.evaModelForm.source_format = "1";
			}

			let ret = await addModelConvert(this.evaModelForm);

			console.log(ret, "retretret");

			// if (this.active == 1) {
			//   this.$refs.evaModelForm.validate(async (valid) => {
			//     if (valid) {
			//       if (this.evaModelForm.type != 1) {
			//         this.evaModelForm.source_format = null
			//         this.evaModelForm.target_format = null
			//       }
			//       // if (this.evaModelForm.type.id != "1") {
			//       //   // 非自定义
			//       // this.evaModelForm.node_group_list = [{
			//       //   "image_id": this.evaModelForm.type.eva_image_id,
			//       //   "command": this.evaModelForm.type.eva_image.command,
			//       //   "product_id": this.node_group_list.product_id,
			//       //   "type": 1,
			//       //   "pod_num": 1
			//       // }]
			//       // } else {
			//       //   this.evaModelForm.type_id = this.evaModelForm.type.id
			//       this.evaModelForm.node_group_list = [this.node_group_list]
			//       // }
			//       console.log("evaModelForm", this.evaModelForm)
			//       let ret = await addModelConvert(this.evaModelForm)
			//       this.evaModelForm = ret.data
			//       if (this.showDiv) {
			//         this.active = 2
			//       } else {
			//         this.toModelEva(ret.data.id, id)
			//       }
			//     }
			//   })
			// } else {
			//   this.toModelEva(this.evaModelForm.id, id)
			// }

			this.showModelEvaDialog = false;

			this.toModelEva(ret.data.id, id);
		},
		toModelEva(model_eva_id, id) {
			let query = {
				model_eva_id,
				id,
			};
			this.$router.push({
				path: "/gameQuantization/code",
				query,
			});
		},
		// 获取模型评估选项
		async getAllModelEvaTypes() {
			let res = await getAllModelEvaluationTypes();
			let data = res.data;
			data.push({ name: "自定义", id: "1" });
			this.modelEvaTyleOptions = data;
			console.log(" this.modelEvaTyleOptions", this.modelEvaTyleOptions);
		},
		// 获取资源组选项
		async getProductList() {
			let res = await getAllProducts();
			this.productOptions = res.data;
		},
		// 评估镜像选项
		async getImageList() {
			let res2 = await getAllImages({ visibility: 2, type: 5 });
			this.imageOptions = res2.data;
		},
		// 修改模型评估类型
		modelEvaTypeChange() {
			if (this.evaModelForm.type.id == "1") {
				this.showDiv = true;
			} else {
				this.showDiv = false;
			}
		},
		async drawerShowHandler(row) {
			this.drawerShow = true;
			this.current = row;
			let res = await getAllModelVersions({ model_id: row.id });
			this.modelAllVersions = res.data;
			console.log("row", res);
		},
		handleChange(val) {
			this.list_flag = val;
		},
		async getData() {
			let res = await getModelConverts({ visibility: this.showThisActive, type: 2 });
			// let res = await getModels({ visibility: this.showThisActive })
			this.tableData = res.data.list;
			this.Pagedata.total = res.data.total;
		},
		searchChange() {
			this.updatePageNum(1);
			this.Pagedata.pageNum = 1;
			this.updateSearch(this.Pagedata.name);
			this.getData();
		},
		async delModel({ id }) {
			// let res = await this.$isDel();
			// if (res) {
			await delModel({ id });
			this.getData();
			// }
		},
		stop(row) {
			console.log(row);
		},
		async del(row) {
			// let res = await this.$isDel();
			// if (res) {
			await delModelConvert(row);
			this.getData();
			// }
		},
		setListOrGraph() {
			this.list_flag = !this.list_flag;
		},
		handleCurrentChange(val) {
			this.Pagedata.pageNum = val;
			this.updatePageNum(val);
			this.getData();
		},
	},
	components: {
		plugDataset,
	},
};
</script>

<style lang="less" scoped>
.switch {
	display: flex;
	justify-content: space-between;

	// overflow: hidden;
	// padding-right: 500px;
	span {
		padding-right: 20px;
	}

	a {
		float: left;
		width: 20px;
		height: 20px;
		margin-left: 14px;
		margin-top: 10px;
		background-color: #767676;
	}

	.btn-pic {
		mask: url(~@/assets/img/file-icon/btn-pic.svg);
		mask-size: 20px 20px;
	}

	.btn-lis {
		mask: url(~@/assets/img/file-icon/btn-lis.svg);
		mask-size: 20px 20px;
	}

	.acticv {
		background-color: #409eff;
	}

	.add-btn {
		float: left;
	}
}

.desc {
	display: -webkit-inline-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	white-space: normal;
	width: 90%;
}

.version-list {
	padding: 0.625rem 0;

	.version-item {
		line-height: 2em;
		padding: 0.625rem 1.25rem;
		border-bottom: 1px solid #eee;
		cursor: pointer;

		&:hover {
			background: #eee;
		}

		p {
			display: flex;
			justify-content: space-between;
			padding: 0.3125rem 0;
		}

		.title {
			font-size: 20px;
		}

		.commit {
			color: #808080;
			display: -webkit-inline-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			white-space: normal;
			width: 90%;
		}
	}
}
</style>
